var Koa = require("koa");
var Router=require("koa-router");
var session = require("koa-session");
var viewEjs = require("koa-views");
var path = require("path");
var bodyparser = require("koa-bodyparser");
var Static = require("koa-static");
var app = new Koa();

//session设置
app.keys = ['this is my secret set']
app.use(session({
  key: 'koa:sess',//cookie key(default is koa:sess)
  maxAge: 86400000,//cookie的过期时间 maxAge in ms（default is 1days）
  overwrite: true,//是否可以overwrite（默认default true）
  httpOnly: true,//cookie是否只有服务端可以访问httpOnly or not （default true）
  signed: true,//签名默认 true
  rolling: false,//在每次请求时强行设置cookie，这将重置cookie过期时间（默认false）
  renew: false,//（boolean）renew session when session is nearly expried
}, app));

//处理传递文件格式
app.use(bodyparser({
	enable:["text","json","form"]
}));

//处理一下静态文件目录（万一有使用图片、样式等是必需的）
app.use(Static(path.resolve(__dirname,"./public")));

//处理模板渲染  ---->然后路由上就可以用router.render了
app.use(viewEjs(path.resolve(__dirname,"./page"),{
	map:{html:"ejs"}
}));


//路由设置
var router=new Router();

router.get("/",async (ctx,next)=>{
	let userSession = ctx.session.user;
	await ctx.render("index",{title:"龙波帝国",userSession});
});
router.get("/user/login",async (ctx,next)=>{
	let userSession = ctx.session.user;
	await ctx.render("login",{});
});
router.post("/user/clogin",async (ctx,next)=>{
	let {username,password} = ctx.request.body;
	if (username == 'longbojun' && password == '54321') {
      ctx.session.user = username;
      ctx.response.redirect('/');
    } else {
      ctx.body = { success: false, msg: '登录失败--账号密码有误' };
    }
});
router.get("/user/logout",async (ctx,next)=>{
	ctx.session.user = null;
    let userSession = ctx.session.user;
    await ctx.render('index', {
      title: '龙波帝国',
      userSession: userSession
    });
});
router.get('/user/userInfo', function (ctx, next) {
  ctx.body = '这是用户详情页，有很多用户信息'
});


router.post("/user/clogin",async (ctx,next)=>{
	let { username, password } = ctx.request.body;
    if (username == '123' && password == '123') {
      ctx.session.user = username;
      ctx.response.redirect('/');
    } else {
      ctx.body = { success: false, msg: '登录失败--账号密码有误' };
    }
});

router.all("/(.*)",async (ctx,next)=>{
	if (!ctx.session.user) {
      ctx.response.redirect('/users/login');
    } else {
      await next();
    }
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3003);
console.log("server is running on 3003!")